#!/usr/bin/env python

import gtk
import pygtk
import facebook as fb
import webbrowser
import gobject

class facebook:
    def __init__(self):
        self.appkey = 'b7b23a01010f3d48a857e4b17f514c18'
        self.secret = '0e44e951fa97f8cb3d0cc2f8f50c7e20'
        self.profile_url = "http://www.facebook.com/profile.php?id=%s"
        self.opensession()

        
    def opensession(self):
        self.book = fb.Facebook(self.appkey, self.secret)
        self.book.auth.createToken()
        self.book.login()
        self.book.auth.getSession()
        self.name = self.book.users.getInfo([self.book.uid], ['name'])[0]['name']
        self.uid = self.book.uid
        self.friendsuid = self.book.friends.get()
        namelist = self.book.users.getInfo(self.friendsuid, ['name'])
        self.friendnameuid = {}
        for item in namelist:
            self.friendnameuid[item['name']] = item['uid'] 

        notes = self.book.notifications.get()
        self.pokes = notes['pokes']['unread']
        self.msgrecent = notes['messages']['most_recent']
        self.msgunread = notes['messages']['unread']
        
    def update(self):
        print "updated"
        self.friendsuid = self.book.friends.get()
        namelist = self.book.users.getInfo(self.friendsuid, ['name'])
        self.friendnameuid = {}
        for item in namelist:
            self.friendnameuid[item['name']] = item['uid'] 

        notes = self.book.notifications.get()
        self.pokes = notes['pokes']['unread']
        self.msgunread = notes['messages']['unread']
        return True
        

        
        
fb_global = facebook()





def delete_cb(widget, event, data = None):
    if data:
        data.set_blinking(True)
        return False
    
def quit_cb(widget, data = None):
    if data:
        data.set_visible(False)
        gtk.main_quit()
        
def popup_menu_cb(widget, button, time, data = None):
    if button == 3:
        if data:
            data.show_all()
            data.popup(None, None, None, 3, time)
        pass
                                                                               
statusIcon = gtk.StatusIcon()


def myprofile_cb(widget, data = None):
    if data:
        webbrowser.open( fb_global.profile_url % data)


def create_completion_model():
    ''' Creates a tree model containing the completions.
    '''
    store = gtk.ListStore(str)
    
    for item in fb_global.friendnameuid.items():
        iter = store.append()
        store.set(iter, 0, item[0])
    return store

def friendsdialog_cb(widget, data = None):
    dialog = gtk.Dialog("Friend Search", None, 0,
                        (gtk.STOCK_OK, gtk.RESPONSE_OK,
                         gtk.STOCK_CANCEL, gtk.RESPONSE_CANCEL))

    dialog.set_resizable(False)

    vbox = gtk.VBox(False, 5)
    dialog.vbox.pack_start(vbox, True, True, 0)
    vbox.set_border_width(5)

            
    label = gtk.Label()
    label.set_markup("View friends profile")
    vbox.pack_start(label, False, False, 0)
    
    # Create our entry
    entry = gtk.Entry()
    vbox.pack_start(entry, False, False, 0)

    # Create the completion object
    completion = gtk.EntryCompletion()
    
    # Assign the completion to the entry
    entry.set_completion(completion)
    
    completion_model = create_completion_model()
    completion.set_model(completion_model)
    
    # Use model column 0 as the text column
    completion.set_text_column(0)
    
    dialog.show_all()

    response = dialog.run()
    if response == gtk.RESPONSE_OK:
        if fb_global.friendnameuid.has_key(entry.get_text()):
            webbrowser.open_new(fb_global.profile_url %
                                      fb_global.friendnameuid[entry.get_text()])
            dialog.destroy()
        else:
            log = gtk.MessageDialog(None, gtk.DIALOG_MODAL | gtk.DIALOG_DESTROY_WITH_PARENT,
                                    gtk.MESSAGE_INFO, gtk.BUTTONS_OK,
                                    "Friend not found in your list" )
            log.run()
            log.destroy()
    


menu = gtk.Menu()
menuItem = gtk.MenuItem(fb_global.name)
menuItem.connect('activate', myprofile_cb, fb_global.uid)
menu.append(menuItem)

menuItem = gtk.MenuItem('friends')
menuItem.connect('activate', friendsdialog_cb, statusIcon)
menu.append(menuItem)


pokesItem = gtk.MenuItem('Pokes %s' % fb_global.pokes)
menu.append(pokesItem)
    
msgunreadItem = gtk.MenuItem('Unread Messages %s' % fb_global.msgunread)
menu.append(msgunreadItem)


def update():
    label = pokesItem.get_children()[0]
    label.set_text('Pokes %s' % fb_global.pokes)
 
    label = msgunreadItem.get_children()[0]
    label.set_text('Unread Messages %s' % fb_global.msgunread)
    return True
    

menuItem = gtk.ImageMenuItem(gtk.STOCK_ABOUT)
#menuItem.connect('activate', activate_icon_cb, statusIcon)
menu.append(menuItem)
menuItem = gtk.ImageMenuItem(gtk.STOCK_QUIT)
menuItem.connect('activate', quit_cb, statusIcon)
menu.append(menuItem)

statusIcon.set_from_stock(gtk.STOCK_HOME)
statusIcon.set_tooltip("Facebook Status")
statusIcon.connect('popup-menu', popup_menu_cb, menu)
statusIcon.set_visible(True)



gobject.timeout_add((60*1*1000), fb_global.update)
gobject.idle_add(update)

gtk.main()
